import json
import os
obj_dir='./label(41-90)_covered/'
name_list=os.listdir(obj_dir)
for name1 in name_list:
    if name1.split('.')[1]=='jpg':
        img_path=obj_dir+name1.split('.')[0]+'.jpg'
        json_path=obj_dir+name1.split('.')[0]+'.json'
        txt_path=obj_dir+name1.split('.')[0]+'.txt'

        row_list=[]
        with open(json_path) as f:
            dict1=json.load(f)
            imageWidth = dict1['imageWidth']
            imageHeight=dict1['imageHeight']
            img_name=dict1['imagePath']
            shapes=dict1['shapes']

            for shape in shapes:
                x1=min(shape['points'][0][0],shape['points'][3][0])/imageWidth
                y1=min(shape['points'][0][1],shape['points'][1][1])/imageHeight
                x2=max(shape['points'][1][0],shape['points'][2][0])/imageWidth
                y2=max(shape['points'][2][1],shape['points'][3][1])/imageHeight
                row1 = [0,(x1+x2)/2,(y1+y2)/2,x2-x1,y2-y1]
                row1=list(map("{:.6f}".format,row1))
                row1[0]=0
                row_list.append(row1)

        with open(txt_path, 'w', newline='') as f:
            for row in row_list:
                for data in row:
                    f.write(str(data))
                    f.write(' ')
                f.write('\r\n')

